<?php

/**
 * Created by PhpStorm.
 * User: feng
 * Date: 2016/12/26
 * Time: 下午6:39
 */
class Lyw_common_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
    }

    public function buildHeaderJson()
    {
        sessionOpen();
        switch ($_SESSION['user_type']) {
            case 1 :
                return $this->yyHeaderJson();
                break;
            case 2:
                return $this->zyHeaderJson();
                break;
            case 3:
                return $this->glHeaderJson();
                break;
            case 4:
                return $this->gzHeaderJson();
                break;
            default:
                exit('Error : not type select header json');
        }
    }

    public function yyHeaderJson()
    {
        $header_json = array(
            'title' => array('url' => site_url('/admin/index')),
            'nav' => array(
                array('li_name' => '主页', 'act' => '', 'a' => site_url('/admin/task')),
                array('li_name' => '个人中心', 'act' => '', 'a' => site_url('/admin/userCenter')),
            ),
            'user' => array(
                'header_img' => empty($_SESSION['header_image']) ? base_url('/assets/header_img/moren.jpeg') : base_url('/assets/header_img/') . $_SESSION['header_image'],
                'user_type' => $_SESSION['user_type'],
            ),
        );
        return $header_json;
    }

    public function zyHeaderJson()
    {
        $header_json = array(
            'title' => array('url' => site_url('/admin/index')),
            'nav' => array(
                array('li_name' => '主页', 'act' => '', 'a' => site_url('/taskworker/task')),
                array('li_name' => '发布任务', 'act' => '', 'a' => site_url('/taskworker/publish')),
                array('li_name' => '个人中心', 'act' => '', 'a' => site_url('/taskworker/userCenter')),
            ),
            'user' => array(
                'header_img' => empty($_SESSION['header_image']) ? base_url('/assets/header_img/moren.jpeg') : base_url('/assets/header_img/') . $_SESSION['header_image'],
                'user_type' => $_SESSION['user_type'],
            ),
        );
        return $header_json;
    }

    public function glHeaderJson()
    {
        $header_json = array(
            'title' => array('url' => site_url('/admin/index')),
            'nav' => array(
                array('li_name' => '用户管理', 'act' => '', 'a' => site_url('/administrator/user')),
                array('li_name' => '任务管理', 'act' => '', 'a' => site_url('/administrator/task')),
//                array('li_name' => '邀请码管理', 'act' => '', 'a' => site_url('/administrator/code')),
                array('li_name' => '公告管理', 'act' => '', 'a' => site_url('/administrator/notice')),
                array('li_name' => '费用中心', 'act' => '', 'a' => site_url('/administrator/tiXian')),
                array('li_name' => '任务专员字数统计', 'act' => '', 'a' => site_url('/administrator/zy_zishutongji')),
            ),
            'user' => array(
                'header_img' => empty($_SESSION['header_image']) ? base_url('/assets/header_img/moren.jpeg') : base_url('/assets/header_img/') . $_SESSION['header_image'],
                'user_type' => $_SESSION['user_type'],
            ),
        );
        return $header_json;
    }

    public function gzHeaderJson()
    {
        $header_json = array(
            'title' => array('url' => site_url('/admin/index')),
            'nav' => array(
//                array('li_name' => '用户管理', 'act' => '', 'a' => site_url('/administrator/user')),
                array('li_name' => '任务管理', 'act' => '', 'a' => site_url('/administrator/task')),
                array('li_name' => '邀请码管理', 'act' => '', 'a' => site_url('/administrator/code')),
//                array('li_name' => '公告管理', 'act' => '', 'a' => site_url('/administrator/notice')),
//                array('li_name' => '费用中心', 'act' => '', 'a' => site_url('/administrator/tiXian')),
//                array('li_name' => '任务专员字数统计', 'act' => '', 'a' => site_url('/administrator/zy_zishutongji')),
            ),
            'user' => array(
                'header_img' => empty($_SESSION['header_image']) ? base_url('/assets/header_img/moren.jpeg') : base_url('/assets/header_img/') . $_SESSION['header_image'],
                'user_type' => $_SESSION['user_type'],
            ),
        );
        return $header_json;
    }

    /**
     * 根据管理表ID来阅读文章,任何类型账号都可以
     */
    public function readOriginalArticleByManagerId()
    {
        $manager_id = isset($_REQUEST['manager_id']) ? $_REQUEST['manager_id'] : '';
        $this->load->model('Lyw_article_manager_model');
        $result = $this->Lyw_article_manager_model->getOneListInfoById($manager_id);
        $this->load->model('Lyw_original_article_model');
        $article = $this->Lyw_original_article_model->getOneListInfoById($result['original_article_id']);
        if (empty($result)) {
            exit('Eorror');
        }
        return $article;
    }

    public function readProofread()
    {
        $manager_id = isset($_REQUEST['manager_id']) ? $_REQUEST['manager_id'] : 0;
        sessionOpen();
        if (empty($manager_id)) {
            exit('empty!');
        }
        $this->load->model('Lyw_article_manager_model');
        $article_manager_info = $this->Lyw_article_manager_model->getOneListInfoById($manager_id);

        /*改内容已经被删除,禁止查看*/
        if ($article_manager_info['is_del'] == 1) {
            exit('is del!');
        }
        /*未到达校对阶段,禁止查看*/
        if ($article_manager_info['translation_article_id'] == 0 || $article_manager_info['original_article_id'] == 0 || $article_manager_info['proofread_article_id'] == 0) {
            exit('Error : illage !');
        }
        $this->load->model('Lyw_translation_article_model');
        $translation_info = $this->Lyw_translation_article_model->getOneListInfoById($article_manager_info['translation_article_id']);
        $this->load->model('Lyw_proofread_article_model');
        $proofread_info = $this->Lyw_proofread_article_model->getOneListInfoById($article_manager_info['proofread_article_id']);
        $this->load->model('Lyw_original_article_model');
        $original_article = $this->Lyw_original_article_model->getOneListInfoById($article_manager_info['original_article_id']);
        $this->lyw_permission_model->readProofreadPermission($article_manager_info['is_proofreaded'], $original_article['original_user_id'], $translation_info['translation_user_id'], $proofread_info['proofread_user_id']);
        $text_number = $this->calculateTextNumber($proofread_info['article_html'], $proofread_info['article_text']);
        $user_id = $_SESSION['user_id'];
        $data = array(
            'user_id' => $user_id,
            'manager_id' => $manager_id,
            'original_article' => $original_article,
            'proofread_info' => $proofread_info,
            'translation_info' => $translation_info,
            'article_manager_info' => $article_manager_info,
            'header_json' => $this->lyw_common_model->buildHeaderJson(),
            'text_number' => $text_number
        );
        return $data;
    }

    /**
     * 计算编辑文字数量
     */
    public function calculateTextNumber($article_html, $article_text)
    {
        /*-------text_number-------*/
        $ar = pregMatchHorizontalLine($article_html);
        $del_number = calculateIconvStrlenByArr($ar);
        $text_number = (iconv_strlen($article_text, 'utf-8') - $del_number);
        return $text_number;
        /*-------text_number-------*/
    }

    public function readTranslation()
    {
        $manager_id = isset($_REQUEST['manager_id']) ? $_REQUEST['manager_id'] : 0;
        sessionOpen();
        if (empty($manager_id)) {
            exit('empyt!');
        }
        $this->load->model('Lyw_article_manager_model');
        $article_manager_info = $this->Lyw_article_manager_model->getOneListInfoById($manager_id);
        if ($article_manager_info['is_del'] == 1) {
            exit('is del!');
        }
        if ($article_manager_info['translation_article_id'] == 0) {
            exit('Error : illage !');
        }
        $this->load->model('Lyw_translation_article_model');
        $translation_info = $this->Lyw_translation_article_model->getOneListInfoById($article_manager_info['translation_article_id']);
        $this->load->model('Lyw_original_article_model');
        $original_article = $this->Lyw_original_article_model->getOneListInfoById($article_manager_info['original_article_id']);
        $this->lyw_permission_model->readTranslationPermission($article_manager_info['is_translationed'], $original_article['original_user_id'], $translation_info['translation_user_id']);
        $user_id = $_SESSION['user_id'];

        $data = array(
            'user_id' => $user_id,
            'manager_id' => $manager_id,
            'original_article' => $original_article,
            'translation_info' => $translation_info,
            'article_manager_info' => $article_manager_info,
            'header_json' => $this->lyw_common_model->buildHeaderJson(),
        );
        return $data;
    }

    public function buildTaskJson($page, $rows)
    {
        $this->load->model('lyw_article_manager_model');
        $manager_list = $this->lyw_article_manager_model->getListInfo($page, $rows);
        $this->load->model('Lyw_original_article_model');
        $this->load->model('Lyw_translation_article_model');
        $this->load->model('Lyw_proofread_article_model');
        $this->load->model('Lyw_user_model');
        /*列表只需添加原文发表者昵称*/
        foreach ($manager_list as $k => &$v) {
            $oa = $this->Lyw_original_article_model->getOneListInfoById($v['original_article_id'], array('original_user_id' , 'creat_time'));
            $oa_user = $this->Lyw_user_model->getUserInfor($oa['original_user_id']);
            $v['oa_name'] = $oa_user['name'];
            $v['oa_creat_time'] = date('Y/m/d', $oa['creat_time']);
            if ($v['translation_article_id'] != 0) {//已经被领取
                $ta = $this->Lyw_translation_article_model->getOneListInfoById($v['translation_article_id'], array('translation_user_id'));
                $ta_user = $this->Lyw_user_model->getUserInfor($ta['translation_user_id']);
                $v['ta_name'] = $ta_user['name'];
            }
        }
        return $manager_list;
    }

    public function addInfoToManagerList(&$manager_list)
    {
        $this->load->model('Lyw_user_model');
        $this->load->model('Lyw_original_article_model');
        $this->load->model('Lyw_translation_article_model');
        foreach ($manager_list as $k => &$v) {
            $oa = $this->Lyw_original_article_model->getOneListInfoById($v['original_article_id']);
            $oa_user = $this->Lyw_user_model->getUserInfor($oa['original_user_id']);
            $v['oa_name'] = $oa_user['name'];
            if ($v['translation_article_id'] != 0) {//已经被领取
                $ta = $this->Lyw_translation_article_model->getOneListInfoById($v['translation_article_id'], array('translation_user_id'));
                $ta_user = $this->Lyw_user_model->getUserInfor($ta['translation_user_id']);
                $v['ta_name'] = $ta_user['name'];
            }
        }
    }

    /**
     * 用户更新权限
     */
    public function userUpPermission($user_id)
    {
        $this->load->model('Lyw_original_article_model');
        $this->load->model('Lyw_translation_article_model');
        $id_array = $this->Lyw_original_article_model->getIdListByUserid($user_id);
        if (!empty($id_array)) {
            //信息存在原文中
            return false;
        }
        $id_array = $this->Lyw_translation_article_model->getIdListByUserid($user_id);
        if (!empty($id_array)) {
            //信息存在翻译中
            return false;
        }
        return true;
    }

    /**
     * 更改头像
     */
    public function changeHeaderImg($file)
    {
        sessionOpen();
        $file_name = time() . rand(1, 9) . '_' . $_SESSION['user_id'] . '_' . $file['name'];
        $fp = fopen(BASEPATH . '../assets/header_img/' . $file_name, 'w+');
        $file_content = file_get_contents($file['tmp_name']);
        fwrite($fp, $file_content);
        fclose($fp);
        $this->load->model('Lyw_user_model');
        $this->Lyw_user_model->updateHeaderImage($_SESSION['user_id'], $file_name);
        return $file_name;
    }

    public function doUserCenter()
    {
        sessionOpen();
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        $school = isset($_POST['school']) ? $_POST['school'] : '';
        $address_life = isset($_POST['address_life']) ? $_POST['address_life'] : '';
        $introduce = isset($_POST['introduce']) ? $_POST['introduce'] : '';
        $professional = isset($_POST['professional']) ? $_POST['professional'] : '';
        $this->load->model('Lyw_user_model');
        if ($name != '' && $school != '' && $address_life != '' && $introduce != '' && $professional != '') {
            $this->Lyw_user_model->updateUserByUserCenter($_SESSION['user_id'], $name, $school, $address_life, $introduce, $professional);
        }
        $user = $this->Lyw_user_model->getUserInfor($_SESSION['user_id']);
        $_SESSION['header_image'] = $user['header_image'];
        $level_arr = calculateLevel($user['jingyan']);
        $data = array(
            'header_json' => $this->buildHeaderJson(),
            'user' => $user,
            'level_arr' => $level_arr
        );
        return $data;
    }

    /**
     * 流程完成,运营工作人员填写阅读量后更新文章管理表,为译员增加稿费
     */
    public function processFinish($manager_id, $read_number, $text_number, $score, $translation_user_id)
    {
        $this->db->trans_start();
        $this->load->model('Lyw_article_manager_model');
        $this->Lyw_article_manager_model->updateReadNumber($manager_id, $read_number);
        /*---计算经验---*/
//        $jingyan_arr = calculateJingYan($score, $text_number);
//        $this->load->model('Lyw_jingyan_record_model');
//        $this->Lyw_jingyan_record_model->insert($manager_id, $translation_user_id, $jingyan_arr['jingyan'], $jingyan_arr['is_add']);
        /*---计算经验---*/
        /*---稿费---*/
        $this->load->model('Lyw_gaofei_record_model');
        $this->load->model('Lyw_user_model');
        $user_list = $this->Lyw_user_model->getUserInfor($translation_user_id);
      
      //  $money = calculateGaoFei($user_list['level'], $score, $text_number, $read_number);
        $money=ceil($read_number * 1);
        $this->Lyw_gaofei_record_model->insert($manager_id, $translation_user_id, $text_number, $score, $read_number, $user_list['level'], $money);
        /*---稿费---*/
        /*--更新用户总的经验值和稿费--*/
//        $this->Lyw_user_model->updateJingYan($translation_user_id, $jingyan_arr['is_add'], $jingyan_arr['jingyan'], $user_list['jingyan']);
        $this->Lyw_user_model->updateGaoFei($translation_user_id, $money);
        /*--更新用户总的经验值--*/
        $this->db->trans_complete();
    }

    /**
     * 处理译员经验
     */
    public function processJingYan($manager_id, $text_number, $score, $translation_user_id)
    {
        $this->db->trans_start();
        $this->load->model('Lyw_user_model');
        $user_list = $this->Lyw_user_model->getUserInfor($translation_user_id);
        /*---计算经验---*/
        $jingyan_arr = calculateJingYan($score, $text_number);
        $this->load->model('Lyw_jingyan_record_model');
        $jingyan_list = $this->Lyw_jingyan_record_model->getInfoByManagerId($manager_id);
        if (empty($jingyan_list)) {
            $this->Lyw_jingyan_record_model->insert($manager_id, $translation_user_id, $jingyan_arr['jingyan'], $jingyan_arr['is_add']);
            $this->Lyw_user_model->updateJingYan($translation_user_id, $jingyan_arr['is_add'], $jingyan_arr['jingyan'], $user_list['jingyan']);
        }
        /*---计算经验---*/
        $this->db->trans_complete();
    }

    /**
     * 领取任务权限 是否存在未完成任务 是否被禁止24小时
     */
    public function getTaskPermission()
    {
        $this->load->model('Lyw_article_manager_model');
        $this->load->model('Lyw_user_model');
        $user = $this->Lyw_user_model->getUserInfor($_SESSION['user_id']);
        if (!empty($user['receive_time']) && $user['receive_time'] != 0 && $user['receive_time'] > time()) {
            //未在领取时间内
            return array('code' => 3, 'receive_time' => $user['receive_time']);
        }
        //寻找最新的未被释放的任务
        $sql = "SELECT creat_time from lyw_translation_article where translation_user_id = {$_SESSION['user_id']} and is_cancel = 0 ORDER BY id desc LIMIT 0 ,1;";
        $translation_list = $this->db->query($sql)->result_array();
        if (($translation_list[0]['creat_time'] + 60 * 60 * 24) > time()) {
//        if (($translation_list[0]['creat_time'] + 1) > time()) {
            return array('code' => 4, 'receive_time' => ($translation_list[0]['creat_time'] + 60 * 60 * 24));
        }
        $list = $this->Lyw_article_manager_model->unfinishedByUserId($_SESSION['user_id'], $_SESSION['user_type']);
        if (empty($list)) {
            return array('code' => 1);
        } else {
            return array('code' => 2);
        }
    }

    /**
     * 翻译越期检查
     */
    public function translationOverDueCheck()
    {
        $this->db->trans_start();
        $this->load->model('Lyw_article_manager_model');
        $this->load->model('Lyw_translation_article_model');
        $this->load->model('Lyw_user_model');
        $this->load->model('Lyw_proofread_article_model');
        $this->load->model('Lyw_original_article_model');

        $manager_list = $this->Lyw_article_manager_model->getTranslationOverDueList();
        foreach ($manager_list as $k => $v) {
            if ($v['is_translationed'] == 1) {
                //翻译中,自动提交
                //翻译员发布了内容,立即将内容增加到校对表内
                $translation_info = $this->Lyw_translation_article_model->getOneListInfoById($v['translation_article_id']);
                $original_article = $this->Lyw_original_article_model->getOneListInfoById($v['original_article_id'], array('original_user_id'));
                $this->Lyw_article_manager_model->changeStatus($v['id'], 'is_translationed', 2);
                $proofread_article_id = $this->Lyw_proofread_article_model->add($original_article['original_user_id'], $translation_info['title'], $translation_info['article_text'], $translation_info['article_html']);
                $this->Lyw_article_manager_model->changeStatus($v['id'], 'proofread_article_id', $proofread_article_id);//添加校对表id
            } else {
                //更新状态
                $this->Lyw_article_manager_model->changeReceivedStatus($v['id'], $v['translation_article_id']);
                //惩罚译员
                $translation_list = $this->Lyw_translation_article_model->getOneListInfoById($v['translation_article_id'], array('translation_user_id'));
                if (!empty($translation_list)) {
                    $this->Lyw_user_model->punishment($translation_list['translation_user_id']);
                }
            }
        }
        $this->db->trans_complete();
    }

    /**
     * 翻译保存权限
     */
    public function translationSavePermission($manager_id, $translation_id, $original_user_id)
    {
        $this->load->model('Lyw_article_manager_model');
        $manager_list = $this->Lyw_article_manager_model->getOneListInfoById($manager_id);
        //检查该用户是否有权限保存
        if ($manager_list['translation_article_id'] != $translation_id) {
            exit(json_encode('Error : failure translation id is wrong! 你无权限进行该操作,请立即关闭当前页面!'));
        }
        //检查是否超时,超时不保存,不发表
        if ($manager_list['translationed_time'] != 0 && $manager_list['translationed_time'] < time()) {
            $this->lyw_common_model->translationOverDueCheck();
            exit(json_encode('Error : failure 翻译超时!请立即关闭当前页面!'));
        }
    }

    /**
     * 领取任务是否弹出提示框
     */
    public function isTheFristReceiveTask($user_id)
    {
        $beginTime = 1485698568; // 2017/1/25日开始算
        if (time() > $beginTime) {
            $this->load->model('Lyw_translation_article_model');
            $id_list = $this->Lyw_translation_article_model->getIdListByUserid($user_id);
            if (empty($id_list)) {
                return true;
            }
            $list = $this->Lyw_translation_article_model->getOneListInfoById($id_list[0], array('creat_time'));
            if (!empty($list) && $list['creat_time'] <= $beginTime) {
                //计算日开始并没有记录,弹框
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 用来手动计算未有添加经验的文章
     */
    public function shouDongJiSuanJingYan()
    {
        $this->db->trans_start();
        $this->load->model("Lyw_jingyan_record_model");
        $this->load->model("Lyw_user_model");
        //计算经验,添加到用户
        $sql = "SELECT a.id , b.jingyan , a.proofreaded_number FROM lyw_article_manager AS a LEFT JOIN lyw_jingyan_record AS b ON a.id = b.manager_id WHERE a.is_del = 0 AND a.is_proofreaded = 2 AND b.jingyan IS NULL ORDER BY a.id DESC LIMIT 0 , 5;";
        $result = $this->db->query($sql)->result_array();
        foreach ($result as $k => $v) {
            $manager_id = $v['id'];
            $proofreaded_number = $v['proofreaded_number'];
            //找到校对得分
            $sql = "SELECT a.id , b.score FROM lyw_article_manager AS  a LEFT JOIN  lyw_proofread_article AS b ON a.proofread_article_id = b.id WHERE a.is_proofreaded = 2 AND a.id = ?;";
            $score = $this->db->query($sql, array($manager_id))->result_array()[0]['score'];
            $jingyan = calculateJingYan($score, $proofreaded_number);
            if(is_array($jingyan)){
                $sql = "SELECT a.id,b.translation_user_id FROM lyw_article_manager AS a LEFT JOIN lyw_translation_article as b ON a.translation_article_id = b.id WHERE a.id = ?;";
                $translation_user_id = $this->db->query($sql, array($manager_id))->result_array()[0]['translation_user_id'];
                //添加到数据库
                $this->Lyw_jingyan_record_model->insert($manager_id, $translation_user_id, $jingyan['jingyan'], $jingyan['is_add']);
                //更新用户经验
                $user = $this->Lyw_user_model->getUserInfor($translation_user_id);
                $this->Lyw_user_model->updateJingYan($translation_user_id, $jingyan['is_add'], $jingyan['jingyan'], $user['jingyan']);
            }
            echo "translation_user_id = {$translation_user_id} and manager_id = {$manager_id} and score = $score and jingyan = {$jingyan['jingyan']} and is_add = {$jingyan['is_add']} <br>";
        }
        $this->db->trans_complete();
    }


    /**
     * 用来手动计算文章校对字数
     */
    public function shouDongJiSuanProofeadNumber()
    {
        $sql = "select * from lyw_article_manager where is_proofreaded = 2 and (proofreaded_number IS NULL or proofreaded_number = 0) ORDER BY id DESC LIMIT 0 , 5";
        $result = $this->db->query($sql)->result_array();
        foreach ($result as $k => $v) {
            $this->load->model('Lyw_proofread_article_model');
            $proofread_info = $this->Lyw_proofread_article_model->getOneListInfoById($v['proofread_article_id']);
            $text_number = $this->calculateTextNumber($proofread_info['article_html'], $proofread_info['article_text']);
            $this->load->model('Lyw_article_manager_model');
            $this->Lyw_article_manager_model->updateProofreadedNumber($v['id'], $text_number);
            echo "text_number = $text_number and proofread_article_id = {$v['proofread_article_id']} and manager_id = {$v['id']} <br>";
        }
    }
}
